package com.example.demo.util;

import com.example.demo.entity.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class MemberUtil {

    // 从请求中获取 Token 并解析为 User 对象
    public static User getUserInfo() {
        // 获取当前请求
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        // 从请求头中获取 Token
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            throw new IllegalArgumentException("Token is missing or empty");
        }
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        // 使用 JwtUtil 解析 Token 并返回 User 对象
        return JwtUtil.getUserFromToken(token);
    }

    /**
     * 假逻辑，也可以用，但是希望实现通过username获取User后返回id来实现
     */
    public static Long getUserId() {
        return getUserInfo().getId();
    }
}